# -*- coding:utf-8 -*-
"""
在使用百度 360时要短信验证
使用时要chrom浏览器关闭，因使用正式环境的浏览器
chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed
 apputils.py中chrome_settings.add_argument('--user-data-dir=C:\\Users\\dell.dell-PC\\AppData\\Local\\Google\\Chrome\\User Data')

"""
from datetime import datetime, timedelta
from flask import Flask, templating
import webbrowser
import store
from appUtils import getWebDriver

app = Flask(__name__, template_folder='', static_folder="", static_url_path='')
indexData = []


def tryData(fun, webProxyDriver):
    """
    返回的格式
    [('2018-12-30', '1'), ('2018-12-27', '1'), ('2018-12-26', '1'), ('2018-12-24', '1'), ('2018-12-23', '1'),
         ('2018-12-21', '2'), ('2018-12-20', '2'), ('2018-12-19', '1'), ('2018-12-17', '5'), ('2018-12-16', '2'),
         ('2018-12-15', '4'), ('2018-12-13', '2'), ('2018-12-12', '1'), ('2018-12-11', '1'), ('2018-12-09', '2'),
         ('2018-12-08', '5'), ('2018-12-07', '6'), ('2018-12-06', '2'), ('2018-12-05', '2'), ('2018-12-04', '14'),
         ('2018-12-03', '53'), ('2018-12-02', '8'), ('2018-12-01', '35'), ('2019-01-16', '1'), ('2019-01-12', '1'),
         ('2019-01-09', '4'), ('2019-01-06', '2'), ('2019-01-05', '3'), ('2019-01-03', '1'), ('2019-01-02', '1')]
    """
    try:
        return fun(webProxyDriver)
    except Exception as e:
        print("error", fun, e)
        # exit()
        return []


def loadData(_vd=True):
    """
    :param _vd: true造个假数据，以免加载时间过长
    :return:
    """
    (browser, proxyServer, _) = getWebDriver(isProxy=True, isMain=True)
    huaweiData = [] if _vd else tryData(store.huawei, webbrowser)
    xiaomiData = [] if _vd else tryData(store.xiaomi, webbrowser)
    oppoData = []
    qqData = [] if _vd else tryData(store.qq, webbrowser)
    baiduData = [] if _vd else tryData(store.baidu, webbrowser)
    qh360 = [] if _vd else tryData(store.qh360, webbrowser)
    appleData = [] if False else tryData(store.apple, webbrowser)
    vivoData = []
    proxyServer.stop()
    webbrowser.quit()
    return [huaweiData, xiaomiData, oppoData, qqData, baiduData, qh360, vivoData, appleData]


def doData(data):
    _dataList = []
    for item in data:
        _dataList.append(dict(item))
    now = datetime.now()

    indexData.append(("日期", "华为", "小米", "OPPO", "应用宝", "百度", "360", "VIVO", "APPLE", "合计"))
    for item in range(8):
        # 日期
        day = now - timedelta(days=item)
        dayTuple = day.timetuple();
        dayStr = str(dayTuple.tm_year) + "-" + str(dayTuple.tm_mon) + "-" + str(dayTuple.tm_mday)
        # 单元格的值
        _item1 = int(_dataList[0][dayStr] if dayStr in _dataList[0] else 0)
        _item2 = int(_dataList[1][dayStr] if dayStr in _dataList[1] else 0)
        _item3 = 0
        _item4 = int(_dataList[3][dayStr] if dayStr in _dataList[3] else 0)
        _item5 = 0
        _item6 = 0
        _item7 = 0
        _item8 = int(_dataList[7][dayStr] if dayStr in _dataList[7] else 0)
        # 列合计
        _itemColumnTotal = _item1 + _item2 + _item3 + _item4 + _item5 + _item6 + _item7 + _item8;
        #
        indexData.append((dayStr, _item1, _item2, _item3, _item4, _item5,
                          _item6, _item7, _item8, _itemColumnTotal))
    # 计算合计
    # 使用列表 元组不能修改值
    rowTotal = ["合计", 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for itemIndex in range(1, len(indexData)):
        item = indexData[itemIndex]
        for index in range(1, len(rowTotal)):
            rowTotal[index] = rowTotal[index] + item[index]
    indexData.append(rowTotal)


@app.route('/')
def main():
    return templating.render_template("index.html", data=indexData, length=range(len(indexData[0])))


if __name__ == '__main__':
    data = loadData(True);
    doData(data)
    print(indexData)
    if (len(indexData) > 2):
        webbrowser.open("http://127.0.0.1:5000")
        app.run()
    else:
        print("任务结束")
